package com.topnav.mc.admin.controller.FullScreenMoniter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.js.lib.cache.Cache;
import com.js.lib.result.ApiResult;
import com.js.lib.result.Result;
import com.topnav.mc.admin.entity.Device;
import com.topnav.mc.admin.entity.DeviceAlarm;
import com.topnav.mc.admin.entity.bean.DeviceAlarmBean;
import com.topnav.mc.admin.entity.param.DeviceAlarmParam;
import com.topnav.mc.admin.security.PermissionGrade;
import com.topnav.mc.admin.service.IDeviceAlarmService;
import com.topnav.mc.admin.service.IDeviceService;
import com.topnav.mc.base.mc.McPage;
import com.topnav.mc.exception.ExceptionMsg;
import com.topnav.mc.system.CpuUsedBean;
import com.topnav.mc.system.MySystemInfo;
import com.topnav.mc.uitls.ErrorResultUtil;
import com.topnav.mc.uitls.PermissionGradeUtil;
import com.topnav.mc.uitls.ResultErrorUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 大屏展示
 * @Author: kenny
 * @Date: 2023/10/9 14:27
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping(value = "admin/fullscreen/monitor")
public class FullScreenMonitorController {
    @Resource(name="localCache")
    private Cache cache;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceAlarmService deviceAlarmService;
    @Autowired
    private PermissionGradeUtil permissionGradeUtil;
    /**
     * 取得硬件信息
     */
    @GetMapping("/get/hardware/info")
    @ResponseBody
    public Result getHardwareData(String orgCode) {
        FullMonitorData resultData = new FullMonitorData();
        MySystemInfo mySystemInfo = (MySystemInfo)cache.get("mySystemInfo");
        if (mySystemInfo == null){
            return Result.ok(resultData);
        }
        resultData.getMemory().setUsed(String.valueOf(Math.round(mySystemInfo.getUsesdMemoryRate() * 100)));
        resultData.getMemory().setFree(String.valueOf(Math.round(mySystemInfo.getFreeMemoryRate() * 100)));

        resultData.getStorage().setUsed(String.valueOf(mySystemInfo.getUsedDisksize()));
        resultData.getStorage().setFree(String.valueOf(mySystemInfo.getFreeDisksize()));
        resultData.setCpu(mySystemInfo.getCpuBean());
        return Result.ok(resultData);
    }

    /**
     * 统计按设备类型注册数量
     * @param orgCode
     * @return
     */
    @GetMapping("/get/device/count/by/cate")
    @ResponseBody
    public Result getDeviceCountByCate(String orgCode) {
        PermissionGrade permissionGrade = permissionGradeUtil.getPmGrade();
        if (permissionGrade == null){
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_AUTHENTICATION_EFFE);
        }

        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("d.cate",2);
        if (permissionGrade != null ){
            if (permissionGrade.getPermissionLevel() == 1){
                queryWrapper.eq("d.user_id",permissionGrade.getUserId());
            }else if (permissionGrade.getPermissionLevel() == 2){
                queryWrapper.eq("d.org_id",permissionGrade.getOrgId());
            }else if (permissionGrade.getPermissionLevel() == 3 || permissionGrade.getPermissionLevel() == 4){
                queryWrapper.likeRight("o.path",permissionGrade.getOrgPath());
            }
        }
        List<ChartDataBean> list = deviceService.countByType(queryWrapper);
        return Result.ok(list);
    }

    /**
     * 按设备类型统计在线数量
     * @return
     */
    @GetMapping("//get/device/count/online/by/cate")
    @ResponseBody
    public Result getDeviceCountOnlineByCate() {
        PermissionGrade permissionGrade = permissionGradeUtil.getPmGrade();
        if (permissionGrade == null){
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_AUTHENTICATION_EFFE);
        }

        QueryWrapper<Device> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("d.cate",2);

        if (permissionGrade.getPermissionLevel() == 1){
            queryWrapper.eq("d.user_id",permissionGrade.getUserId());
        }else if (permissionGrade.getPermissionLevel() == 2){
            queryWrapper.eq("d.org_id",permissionGrade.getOrgId());
        }else if (permissionGrade.getPermissionLevel() == 3 || permissionGrade.getPermissionLevel() == 4){
            queryWrapper.likeRight("o.path",permissionGrade.getOrgPath());
        }

        int allNum=0;
        //所有已注册
        List<ChartDataBean> listAll = deviceService.countAll(queryWrapper);
        if (!CollectionUtils.isEmpty(listAll)){
            allNum = listAll.get(0).getValue();
        }
        //只查在线
        queryWrapper.eq("d.online",true);
        List<ChartDataBean> list = deviceService.countByType(queryWrapper);
        int onlineNum=0;
        for(ChartDataBean chartDataBean : list){
            onlineNum = onlineNum + chartDataBean.getValue();
        }
        String msg=String.valueOf(onlineNum) + "/" + String.valueOf(allNum);
        return Result.ok(msg,list);
    }

    /**
     * 按报警类型统一报警数量
     * @return
     */
    @GetMapping("/get/device/alarm/count/by/cate")
    @ResponseBody
    public Result getDeviceAlarmCountByCate() {
        PermissionGrade permissionGrade = permissionGradeUtil.getPmGrade();
        if (permissionGrade == null){
            return ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_EFFE);
        }

        QueryWrapper<DeviceAlarm> queryWrapper = new QueryWrapper<>();
        if (permissionGrade.getPermissionLevel() == 1){
            queryWrapper.eq("d.user_id",permissionGrade.getUserId());
        }else if (permissionGrade.getPermissionLevel() == 2){
            queryWrapper.eq("d.org_id",permissionGrade.getOrgId());
        }else if (permissionGrade.getPermissionLevel() == 3 || permissionGrade.getPermissionLevel() == 4){
            queryWrapper.likeRight("o.path",permissionGrade.getOrgPath());
        }
        //查询一周的数据
        Date to = new Date();
        Date from = new Date(to.getTime() - 7 * 24 * 60 *60 *1000);
        queryWrapper.ge("a.alarm_time",from).le("a.alarm_time",to);
        return Result.ok(deviceAlarmService.countGroupByCateList(queryWrapper));
    }
    /**
     * 按部门统计设备数量
     * @return
     */
    @GetMapping("/get/device/count/by/org")
    @ResponseBody
    public Result getDeviceCountByOrg() {
        PermissionGrade permissionGrade = permissionGradeUtil.getPmGrade();
        if (permissionGrade == null) {
            return ErrorResultUtil.result(ExceptionMsg.ERROR_AUTHENTICATION_EFFE);
        }
        QueryWrapper<DeviceAlarm> queryWrapper = new QueryWrapper<>();
        if (permissionGrade.getPermissionLevel() == 1){
            queryWrapper.eq("d.user_id",permissionGrade.getUserId());
        }else if (permissionGrade.getPermissionLevel() == 2){
            queryWrapper.eq("d.org_id",permissionGrade.getOrgId());
        }else if (permissionGrade.getPermissionLevel() == 3 || permissionGrade.getPermissionLevel() == 4){
            queryWrapper.likeRight("o.path",permissionGrade.getOrgPath());
        }
        queryWrapper.eq("d.cate",2);
        List<ChartDataBean> list = deviceService.countByOrg(queryWrapper);

        return Result.ok(list);

    }
    /**
     * 实时报警数据列表
     * @return
     */
    @GetMapping("/get/device/alarm/actual/for/chart")
    @ResponseBody
    public Result getDeviceAlarmActualForChart(){
        PermissionGrade permissionGrade = permissionGradeUtil.getPmGrade();
        if (permissionGrade == null){
            return ResultErrorUtil.byExceptionMsg(ExceptionMsg.ERROR_AUTHENTICATION_EFFE);
        }
        QueryWrapper<DeviceAlarmParam> queryWrapper = new QueryWrapper<>();
        if (permissionGrade.getPermissionLevel() == 1){
            queryWrapper.eq("d.user_id",permissionGrade.getUserId());
        }else if (permissionGrade.getPermissionLevel() == 2){
            queryWrapper.eq("d.org_id",permissionGrade.getOrgId());
        }else if (permissionGrade.getPermissionLevel() == 3 || permissionGrade.getPermissionLevel() == 4){
            queryWrapper.likeRight("o.path",permissionGrade.getOrgPath());
        }
        Date to = new Date();
        Date from = new Date(to.getTime() - 7 * 24 * 60 *60 *1000);
        queryWrapper.ge("a.alarm_time",from).le("a.alarm_time",to);
        queryWrapper.orderByDesc("a.id");

        Page<DeviceAlarmParam> page = new Page();
        page.setCurrent(0);
        page.setSize(15);
        Page<DeviceAlarmBean> page1 = deviceAlarmService.pageInfo(page,queryWrapper);

        return Result.ok(page1.getRecords());
    }



    @Data
    public static class FullMonitorData{
        private Date actionTime=new Date();
        private CommData memory = new CommData();
        private CommData storage = new CommData();
        private List<CpuUsedBean> cpu = new ArrayList<>();
    }

    @Data
    public static class CommData{
        private String used="50";
        private String free="50";

    }


}
